<template>
  <div class="app-container">
    <div class="create-container">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
        <el-row type="flex" justify="center">
          <el-col :span="16">
            <el-row>
              <el-form-item prop="name" style="margin-bottom:20px">
                <template #label>
                  <strong>{{ $t('name') }}</strong>
                </template>
                <el-input v-model="ruleForm.name" :placeholder="$t('method_name')" type="text" />
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <!--            <el-row>-->
          <!--              <el-form-item :label="$t('content')" prop="content" style="margin-bottom:20px">-->
          <!--                <Editor v-model="ruleForm.content" :init="tinymce_init" />-->
          <!--              </el-form-item>-->
          <!--            </el-row>-->
          <el-col :span="16">
            <el-row>
              <el-form-item prop="content" style="margin-bottom:20px">
                <template #label>
                  <strong>{{ $t('content') }}</strong>
                </template>
                <el-table class="draggable custom-table" row-key="id" :data="ruleForm.content_json" stripe style="width: 100%">
                  <!-- 第i个任务 -->
                  <el-table-column
                    :label="$t('Subtask_list')"
                    prop="name"
                    align="left"
                    min-width="80%"
                  >
                    <template slot-scope="scope">
                      <div class="task-container">
                        <span class="task-number">{{ scope.$index + 1 }}</span>
                        <el-input v-model="scope.row.task_detail" type="textarea" :placeholder="$t('enter_task')" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    min-width="20%"
                  >
                    <template slot="header">
                      <div class="header-buttons">
                        <el-button type="primary" size="mini" @click="pushPara">{{ $t('new') }}</el-button>
                      </div>
                    </template>
                    <template slot-scope="scope">
                      <div class="cell-buttons">
                        <el-button size="mini" type="danger" @click="popPara(scope.$index)">{{ $t('delete') }}</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>

              </el-form-item>
            </el-row>
            <el-row type="flex" justify="right">
              <el-form-item>
                <el-button type="primary" style="margin-bottom: 20px" @click="submitForm('ruleForm')">
                  {{ $t('save') }}
                </el-button>
                <!--            <el-button type="primary" @click="goBack()">返回</el-button>-->
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
// import { createNewTemplate } from '@/api/chart'
// import { Message } from 'element-ui'
import Editor from '@tinymce/tinymce-vue'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver'
import 'tinymce/icons/default/icons.min.js'
import 'tinymce/models/dom/model'
import { createMethodologies } from '@/api/methodology'
import Sortable from 'sortablejs'

export default {
  components: {
    Editor
  },
  data() {
    return {
      tinymce_init: {
        language_url: '/tinymce/langs/zh-Hans.js',
        branding: false,
        promotion: false,
        toolbar: false,
        forced_root_block: ' ',
        skin_url: '/tinymce/skins/ui/oxide',
        content_css: 'tinymce/skins/content/default/content.css',
        language: 'zh-Hans'
        // plugins: 'lists link image table code help wordcount '
      },
      ruleForm: {
        name: '',
        content: '',
        content_json: []
      },
      rules: {
        name: [
          { required: true, message: (this.$t('name_rule') + '!'), trigger: 'blur' }
        ],
        content: [
          // 这里是一个函数，而不是一个数组
          { required: true, validator: (rule, value, callback) => {
            // 调用 validateContent 函数进行验证
            const isValid = this.validateContent()
            if (isValid) {
              callback(new Error(this.$t('description_rule') + '!'))
            } else {
              callback()
            }
          }, trigger: 'blur' }
        ]
        // content: [
        //   { required: true, message: ('内容不能为空!'), trigger: 'blur' }
        // ]
      }
    }
  },

  mounted() {
    // tinymce.init({})
    this.$nextTick(() => {
      this.rowDrop()
    })
  },
  methods: {
    // 行拖拽
    rowDrop() {
      // 正确选择 tbody 元素
      const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody')
      const _this = this
      // const tbody = this.$el.querySelector('.draggable .el-table__body-wrapper tbody')
      // console.log(tbody)
      if (tbody) {
        // 使用 Sortable.js 库来实现拖拽功能
        // eslint-disable-next-line new-cap
        new Sortable.create(tbody, {
          // 指定可被拖拽的子元素
          draggable: 'tbody .el-table__row',
          // animation: 150, // 动画效果的持续时间
          onEnd({ newIndex, oldIndex }) {
            // console.log('1111111111')
            const currRow = _this.ruleForm.content_json.splice(oldIndex, 1)[0]
            _this.ruleForm.content_json.splice(newIndex, 0, currRow)
          }
        })
      } else {
        console.error('Table body not found')
      }
    },
    pushPara() {
      // 确保ruleForm.content是一个数组
      if (!Array.isArray(this.ruleForm.content_json)) {
        this.ruleForm.content_json = []
      }
      // 向ruleForm.content数组中添加一个新的对象
      this.ruleForm.content_json.push({
        id: this.ruleForm.content_json.length + 1, // 假设id是连续的
        task_detail: '' // 新行的初始任务详情为空
      })
      console.log(this.ruleForm.content_json)
    },
    // 删除参数
    popPara(index) {
      this.ruleForm.content_json.splice(index, 1)
    },
    validateContent() {
      // 检查所有task_detail是否为空
      const allTaskDetailsEmpty = this.ruleForm.content_json.every(item => !item.task_detail)

      console.log(allTaskDetailsEmpty)
      return allTaskDetailsEmpty
    },
    submitForm(formName) {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.ruleForm.content_json.forEach((item, index) => {
            item.id = index + 1 // id 从 1 开始，基于数组的新索引
          })
          // 检查所有task_detail是否为空
          const allTaskDetailsEmpty = this.ruleForm.content_json.every(item => !item.task_detail)

          if (allTaskDetailsEmpty) {
            // console.log("所有task均为空")
            // 如果所有task_detail都为空，触发验证失败
            this.$refs[formName].validateField('content', (error) => {
              if (error) {
                this.$message({
                  message: this.$t('description_rule') + '!',
                  type: 'error'
                })
              }
            })
            return
          } else {
            const taskDetailsArray = this.ruleForm.content_json.map(item => item.task_detail)
            // 使用分号连接所有的 task_detail
            const taskDetails = taskDetailsArray.join('；')

            console.log(taskDetails)
            this.$confirm(this.$t('methodology_create_tips'), this.$t('tip'), {
              confirmButtonText: this.$t('confirm'),
              cancelButtonText: this.$t('cancel'),
              type: 'warning',
              closeOnClickModal: false
            }).then(() => {
              let methodology = {
                'name': this.ruleForm.name,
                'content': taskDetails,
                'content_json': JSON.stringify(this.ruleForm.content_json),
                'creator_id': this.$store.getters.id
              }
              methodology = JSON.stringify(methodology)
              console.log(methodology)
              createMethodologies(methodology).then(response => {
                console.log(response.data)
                // 路由至上一页面
                this.$router.push({ path: '/methodology/index' })
                this.$message({
                  message: this.$t('create_success_tips'),
                  type: 'success'
                })
              }).catch(error => {
                console.log(error)
                this.$message({
                  message: this.$t('create_error_tips'),
                  type: 'error'
                })
              })
            }).catch(() => {
              this.$message({
                message: this.$t('submit_cancel_tips'),
                type: 'info'
              })
            })
          }
        } else {
          return false
        }
      })
    }
    // goBack() {
    //   this.$router.push({ path: '/service/template' })
    // }
  }
}
</script>

<style>
.create-container {
  margin-top: 20px;
  background-color: white;
  padding-top: 20px;
}
.descriptions {
  margin-top: 15px
}

.rule-form {
  width: 900px
}

.el-upload {
  width: 100%;
}

.el-upload .el-upload-dragger {
  width: 100%;
}

.el-row {
  margin-bottom: 2px; /* 例如增加底部间距 */
}

/* Add or modify this in your <style> section */
.el-form-item {
  margin-bottom: 10px; /* Increase or decrease the bottom margin as needed */
}

/* Adjust the checkbox positioning */
.el-form-item input[type="checkbox"] {
  margin-right: 5px; /* Increase or decrease the right margin as needed */
  vertical-align: middle; /* Align the checkbox vertically */
}

.el-form-item label {
  display: inline-block; /* Ensure the label and checkbox stay in line */
  vertical-align: middle; /* Align the label vertically */
  color: gray; /* 设置复选框字体颜色为灰色 */
  font-weight: normal;
}
.el-table__row {
  cursor: move; /* 添加鼠标指针样式，表示可以拖拽 */
}
.task-container {
  display: flex;
  align-items: center;
}

.task-number {
  margin-right: 18px;
  margin-left: 10px;
}

.header-buttons, .cell-buttons {
  display: flex;
  justify-content: flex-end; /* 使按钮右对齐 */
  margin-right: 10px;
  /*align-items: center; !* 垂直居中对齐 *!*/
}

.el-table .el-table__body-wrapper {
  overflow-x: hidden; /* 隐藏横向滚动条 */
}
.el-table {
  table-layout: fixed; /* 固定表格布局，防止内容溢出 */
}

.custom-table {
  border: 1px  solid #dcdfe6; /* 边框颜色 */
  border-radius: 5px;
  /*border-collapse: collapse; !* 边框合并 *!*/
}
</style>
